#!/user/bin/env python
# coding:utf-8
"""
Author myYouTh
Date:2020/2/21 002111:42
Desc: 读取yaml文件，并解析出测试用例的请求数据
"""

import yaml
import os


def _readtestdatayaml(yamlfimename) -> dict:
    """从yaml文件中读取测试用例"""
    filepath = os.path.join(os.path.dirname(os.path.dirname(__file__)), "testdata", yamlfimename)

    try:
        with open(file=filepath, mode='r', encoding="utf-8") as file:
            yaml_result = yaml.load(stream=file, Loader=yaml.FullLoader)
            return yaml_result
    except Exception:
        raise NameError(f"{yamlfimename}文件打开失败")


def getyamlAllTestCase(yamlfilename):
    """从yaml文件中取出测试用例的请求数据"""
    result = {}
    testdatayaml = _readtestdatayaml(yamlfilename)
    try:
        for key in testdatayaml:
            # key表示测试用例名称
            # 检查到是测试用例
            if "test" in key:
                result[key] = {"request": {}, "expect": {}}
                result[key]["request"]["requestmethod"] = testdatayaml[key]["request"]["method"]
                result[key]["request"]["requesthost"] = testdatayaml[key]["request"]["host"]
                result[key]["request"]["requestinterface"] = testdatayaml[key]["request"]["interface"]
                result[key]["request"]["requestheader"] = testdatayaml[key]["request"]["header"]
                result[key]["request"]["requestdata"] = testdatayaml[key]["request"]["data"]
                result[key]["expect"] = testdatayaml[key]["expect"]
        else:
            return result
    except KeyError:
        raise KeyError("字典键不存在，请仔细检查yam文件中测试用例的格式是否正确")


